/**
 * 
 */
package daily.web.validator;

import java.util.*;
import java.util.regex.*;

import javax.enterprise.context.*;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.inject.*;

import org.omnifaces.validator.*;

import daily.service.*;

/**
 * @author xiaopengzhu
 * 
 */
@ApplicationScoped
@Named("timeRangeValidator")
public class TimeRangeValidator implements MultiFieldValidator {
	private static final Pattern VALID_TIME = Pattern.compile("[012][0-9]:[0-5][0-9]");

	private String message;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.omnifaces.validator.MultiFieldValidator#validateValues(javax.faces
	 * .context.FacesContext, java.util.List, java.util.List)
	 */
	@Override
	public boolean validateValues(final FacesContext arg0, final List<UIInput> arg1, final List<Object> arg2) {
		final String startTime = (String) arg2.get(0);
		final String endTime = (String) arg2.get(1);
		if (checkTime(startTime) == false || checkTime(endTime) == false) {
			return false;
		}
		final TimeRange timeRange = TimeRange.valueOf(startTime, endTime);
		if (toMinutes(timeRange.getStartTime()) > toMinutes(timeRange.getEndTime())) {
			message = "終了時間が開始時間以降のを入力してください。";
			return false;
		}
		return true;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(final String message) {
		this.message = message;
	}

	private boolean checkTime(final String time) {
		if (time != null) {
			if (VALID_TIME.matcher(time).matches() == false) {
				message = "時間を正しく入力してください。";
				return false;
			}
		}
		return true;
	}

	private int toMinutes(final String time) {
		return Integer.valueOf(time.substring(0, 2)) * 60 + Integer.valueOf(time.substring(3));
	}
}
